import React from 'react'
import PropTypes from 'prop-types'
import {
    Form, Input, Button, message,
} from 'antd'
import axios from 'axios'
import { connect } from 'react-redux'

function Index(props) {
    const layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 8 },
    }
    const tailLayout = {
        wrapperCol: { offset: 8, span: 16 },
    }
    const onFinish = (values) => {
        if (values.password === values.password2) {
            // 两次密码输入一致
            props.register(values)
        } else {
            message.error('两次密码输入不一致')
        }
    }
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo)
    }
    return (
        <div>
            <h3>注册</h3>
            <Form
                {...layout}
                name="basic"
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >
                <Form.Item
                    label="用户名"
                    name="username"
                    rules={[{ required: true, message: '请输入用户名' }]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="密码"
                    name="password"
                    rules={[{ required: true, message: '请输入密码' }]}
                >
                    <Input.Password />
                </Form.Item>
                <Form.Item
                    label="再次输入密码"
                    name="password2"
                    rules={[{ required: true, message: '请再次输入密码' }]}
                >
                    <Input.Password />
                </Form.Item>

                {/* <Form.Item {...tailLayout} name="remember" valuePropName="checked">
        <Checkbox>Remember me</Checkbox>
      </Form.Item> */}

                <Form.Item {...tailLayout}>
                    <Button type="primary" htmlType="submit">
            Submit
                    </Button>
                </Form.Item>
            </Form>
        </div>
    )
}
const mapStateToProps = () => ({

})
const mapDispatchToProps = (dispatch, props) => ({
    register(obj) {
        dispatch(() => {
            axios.post('/register', {
                name: obj.username,
                password: obj.password,
            }).then((res) => {
                if (res.data.code === 1) {
                    props.history.push('/login')
                    console.log('注册成功')
                } else {
                    console.log('注册失败')
                }
            })
        })
    },
})
Index.propTypes = {
    register: PropTypes.func,
}
export default connect(mapStateToProps, mapDispatchToProps)(Index)
